/**
 * 新增编辑页
 */
import React from 'react';
import { Form, Card, Button, message, Radio, Divider } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import pageTabUtil from '@/utils/pageTabUtil';
import { useRequest, defaultFormatResult } from '@/hooks';
import { BottomAction } from '@/components';
import CancelEditConfirm from '@/components/CancelEditConfirm';
import { FormHeader } from '@/molecules';
import { useFormChange } from '../hooks';
import { getRule, addRule, getExistCompanyCodes } from './services';
import { BraftTemplate, Base, Info, Evaluation, Result, Performance, Attendance } from '../containers';
import styles from './index.less';

const InformalRuleEdit = ({ form, location }) => {
    const { query } = location;
    const { getFieldDecorator } = form;
    const [editorValue, setEditorValue] = React.useState('');
    const [flag, setFlag] = React.useState(false);
    const { id } = query || {};
    const modelId = React.useMemo(() => id || new Date().getTime(), [id]);

    const evaluationRef = React.useRef();

    const isAddPage = React.useMemo(() => {
        const { pathname = '' } = location;
        return pathname.includes('add');
    }, [location]);

    const { hasFormChange, initialForm } = useFormChange(form);

    const { data, loading } = useRequest(() => getRule(query?.id), {
        refreshDeps: [query?.id],
        ready: !!query?.id,
        ...defaultFormatResult,
        onSuccess: res => {
            setEditorValue(res?.templateContent || '');
            initialForm();
        }
    });

    const { data: usedList, run: fetchUsedList } = useRequest(() => getExistCompanyCodes(), {
        manual: true,
        initialData: [],
        formatResult: res => {
            if (res) {
                const { code, msg } = res;
                if (code === 10000) {
                    return res.data;
                }
                message.error(msg);
            }
            return [];
        }
    });

    React.useEffect(() => {
        fetchUsedList();
    }, []);

    const { loading: saveLoading, run: saveTemplate } = useRequest(addRule, {
        manual: true,
        onSuccess: res => {
            const { code, msg } = res;
            if (code === 10000) {
                message.success('操作成功');
                pageTabUtil.goBack();
                return;
            }
            message.error(msg);
        }
    });

    const handleCheck = () => {
        form.validateFieldsAndScroll({ scroll: { alignWithTop: true } }, async (err, values) => {
            const {
                applyRuleConfigVO,
                taskAssessVO,
                quarterlyPerformanceAssessVO,
                attendanceAssessVO,
                ...rest
            } = values;

            const taskAssessDetail = [1, 2, 3].map(item => ({
                monthValue: values?.[`monthValue${item}`],
                quarterValue: values?.[`quarterValue${item}`],
                type: item,
                weekValue: values?.[`weekValue${item}`]
            }));
            const attendanceDetail = [1, 2, 3, 4, 5].map(item => ({
                monthValue: values?.[`monthValueAttendance${item}`],
                quarterValue: values?.[`quarterValueAttendance${item}`],
                type: item,
                weekValue: values?.[`weekValueAttendance${item}`]
            }));

            // 去除多余参数
            const restParams = { ...rest };
            Object.keys(restParams).forEach(c => {
                const param = c.toString();
                if (
                    param.startsWith('weekValue') ||
                    param.startsWith('monthValue') ||
                    param.startsWith('quarterValue')
                ) {
                    delete restParams[param];
                }
            });

            const params = {
                ...restParams,
                applyRuleConfigDTO: {
                    ...applyRuleConfigVO,
                    content: editorValue
                        .replace(/<span data-foo="/g, '${')
                        .replace(/" data-id="[0-9]+" class="column-item">[\u4e00-\u9fa5]+<\/span>/g, '}')
                },
                taskAssessDTO: {
                    ...taskAssessVO,
                    detail: taskAssessDetail
                },
                quarterlyPerformanceAssessDTO: quarterlyPerformanceAssessVO,
                attendanceAssessDTO: {
                    ...attendanceAssessVO,
                    detail: attendanceDetail
                }
            };
            if (!err) {
                if (!isAddPage) {
                    params.id = query?.id;
                }
                saveTemplate(params);
            }
        });
    };

    const handleSubmit = () => {
        setFlag(true);
        handleCheck();
    };

    const handleChange = React.useCallback(
        html => {
            setEditorValue(html);
            if (!flag && html && html !== '<p></p>') {
                setFlag(true);
            }
        },
        [flag]
    );

    const handleBlur = React.useCallback(() => setFlag(true), []);

    React.useEffect(() => {
        initialForm();
    }, []);

    const isPassed =
        !flag ||
        (editorValue &&
            editorValue !== '<p></p>' &&
            editorValue !==
                '<p size="0" _root="undefined" __ownerID="undefined" __hash="undefined" __altered="false"></p>');

    const initialStr =
        // eslint-disable-next-line no-template-curly-in-string
        '<p></p><table border="1" style="border-collapse: collapse"><colgroup><col width="165"></col><col width="235"></col><col width="165"></col><col width="235"></col></colgroup><tr><td style="text-align:right;" colSpan="1" rowSpan="1">员工姓名：</td><td colSpan="1" rowSpan="1">${employeeName}</td><td style="text-align:right;" colSpan="1" rowSpan="1">行政机构：</td><td colSpan="1" rowSpan="1">${companyName}</td></tr><tr><td style="text-align:right;" colSpan="1" rowSpan="1">组织机构：</td><td colSpan="1" rowSpan="1">${organizationName}</td><td style="text-align:right;" colSpan="1" rowSpan="1">岗位：</td><td colSpan="1" rowSpan="1">${dutyName}</td></tr><tr><td style="text-align:right;" colSpan="1" rowSpan="1">入职日期：</td><td colSpan="1" rowSpan="1">${entryDate}</td><td style="text-align:right;" colSpan="1" rowSpan="1">转正日期：</td><td colSpan="1" rowSpan="1">${expectRegularDate}</td></tr><tr><td style="text-align:right;" colSpan="1" rowSpan="1">试用期工作总结：</td><td colSpan="3" rowSpan="1"><br/><br/></td></tr><tr><td style="text-align:right;" colSpan="1" rowSpan="1">需要改进的地方：</td><td colSpan="3" rowSpan="1"><br/><br/></td></tr><tr><td style="text-align:right;" colSpan="1" rowSpan="1">对公司的意见：</td><td colSpan="3" rowSpan="1"><br/><br/></td></tr><tr><td style="text-align:right;" colSpan="4" rowSpan="1"><br/>员工签名：                              日期：                      <br/></td></tr></table><p></p>';

    return (
        <PageHeaderWrapper>
            <Card
                title={isAddPage ? '新增转正规则' : '编辑转正规则'}
                bordered={false}
                loading={loading}
                extra={
                    <BottomAction>
                        <CancelEditConfirm>
                            <Button
                                disabled={saveLoading}
                                onClick={e => {
                                    if (!hasFormChange()) {
                                        e.stopPropagation();
                                        pageTabUtil.goBack();
                                    }
                                }}
                            >
                                取消
                            </Button>
                        </CancelEditConfirm>

                        <Button type="primary" onClick={handleSubmit} loading={saveLoading}>
                            保存
                        </Button>
                    </BottomAction>
                }
            >
                <FormHeader title="基本信息" />
                <Info
                    form={form}
                    data={data}
                    className={styles.formWrap}
                    disabledKeys={usedList}
                    style={{ maxWidth: 800 }}
                />
                <Divider />
                <FormHeader title="试用期设置" />
                <Base form={form} data={data} className={styles.formWrap} style={{ maxWidth: 800 }} />
                <Divider />
                <FormHeader title="转正考评指标" />
                <div style={{ padding: '0 0 24px 0', maxWidth: 1080 }}>
                    <FormHeader title="能力评估：" style={{ fontSize: 14 }} />
                    <Evaluation
                        form={form}
                        ref={evaluationRef}
                        data={data}
                        modelId={modelId}
                        className={styles.formWrap}
                    />
                    {/* <Divider /> */}
                    <FormHeader title="任务结果：" style={{ fontSize: 14 }} />
                    <Result form={form} data={data} className={styles.formWrap} />
                    <Divider />
                    <FormHeader title="季度绩效：" style={{ fontSize: 14 }} />
                    <Performance form={form} data={data} className={styles.formWrap} />
                    <Divider />
                    <FormHeader title="考勤情况：" style={{ fontSize: 14 }} />
                    <Attendance form={form} data={data} className={styles.formWrap} />
                </div>
                <Divider />
                <FormHeader title="转正申请表设置" />
                <Form className={styles.formWrap}>
                    <Form.Item
                        label="转正申请表"
                        help={
                            form.getFieldValue('applyRuleConfigVO.fillInRule') !== 2 || isPassed
                                ? ''
                                : '转正申请表不能为空'
                        }
                        validateStatus={
                            form.getFieldValue('applyRuleConfigVO.fillInRule') !== 2 || isPassed ? '' : 'error'
                        }
                        required={form.getFieldValue('applyRuleConfigVO.fillInRule') === 2}
                    >
                        <BraftTemplate
                            prefix="rule"
                            onBlur={handleBlur}
                            onChange={handleChange}
                            placeholder="请输入转正申请表"
                            initialValue={data?.applyRuleConfigVO?.content || initialStr}
                        />
                    </Form.Item>
                    <Form.Item label="填写规则">
                        {getFieldDecorator('applyRuleConfigVO.fillInRule', {
                            initialValue:
                                typeof data?.applyRuleConfigVO?.fillInRule === 'undefined'
                                    ? 1
                                    : data?.applyRuleConfigVO?.fillInRule,
                            rules: [
                                {
                                    required: true,
                                    message: '请选择填写规则'
                                }
                            ]
                        })(
                            <Radio.Group>
                                <Radio value={0}>无需填写</Radio>
                                <Radio value={1}>选填</Radio>
                                <Radio value={2}>必填</Radio>
                            </Radio.Group>
                        )}
                        <div style={{ lineHeight: 1.5, fontSize: 12, color: 'rgba(0, 0, 0, 0.25)' }}>
                            注：①选择无需填写，新员工在转正申请流程中，不出现填写转正申请表的内容；
                            <br />
                            <span style={{ display: 'inline-block', width: '2em' }}></span>
                            ②选择选填，新员工在转正申请流程中，出现填写转正申请表的内容，但非必填；
                            <br />
                            <span style={{ display: 'inline-block', width: '2em' }}></span>
                            ③选择必填，新员工在转正申请流程中，出现并必须填写转正申请表的内容。
                        </div>
                    </Form.Item>
                </Form>
            </Card>
        </PageHeaderWrapper>
    );
};

export default Form.create({})(InformalRuleEdit);
